package com.zhijian.medical.service.impl;

import cn.hutool.core.date.DateTime;
import com.zhijian.medical.dao.local.PhLocationMapper;
import com.zhijian.medical.entity.po.LocationInsertVo;
import com.zhijian.medical.entity.po.LocationUpdateVo;
import com.zhijian.medical.entity.po.PhLocation;
import com.zhijian.medical.entity.vo.response.LocationVo;
import com.zhijian.medical.enums.ResponseCodeEnum;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.service.LocationService;
import com.zhijian.medical.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author HCG
 * @version 1.0
 * @date 2021/7/21
 */
@Service
@Slf4j
public class LocationServiceImpl implements LocationService {

    @Autowired
    private PhLocationMapper mapper;

//    @Autowired
//    private DeviceService deviceService;

    @Override
    public List<LocationVo> selectListByParentId(Long parentId) {
        return mapper.selectListByParentId(parentId);
    }

    /**
     * 树形查询
     *
     * @param all
     * @param pid
     * @return
     */
    @Override
    public List<LocationVo> selectTreeList(List<LocationVo> all, Long pid) {
        return createTree(all, pid);
    }

    @Override
    public List<LocationVo> selectTreeList(List<LocationVo> all, Long pid, boolean isContainsCamera) {
        return createTree(all, pid, isContainsCamera);
    }

    @Override
    public List<LocationVo> renderTreeList() {
        List<LocationVo> locationVos = this.selectListByParentId(null);
        Collections.reverse(locationVos);
        return selectTreeList(locationVos, 0L);
    }

    @Override
    public List<LocationVo> renderTreeList(boolean isContainsCamera) {
        List<LocationVo> locationVos = this.selectListByParentId(null);
        Collections.reverse(locationVos);
        return selectTreeList(locationVos, 0L, isContainsCamera);
    }

    @Override
    public boolean insert(LocationInsertVo locationInsertVo) {
        if (BeanUtil.isNull(locationInsertVo)) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "数据为空");
        }
        if (0 != locationInsertVo.getParentId() && BeanUtil.isNull(mapper.selectByPrimaryKey(locationInsertVo.getParentId()))) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "选择的父级不存在或者已被删除");
        }
        Date now = DateTime.now();
        return mapper.insert(PhLocation.builder()
                .createTime(now)
                .updateTime(now)
                .name(locationInsertVo.getName())
                .parentId(locationInsertVo.getParentId())
                .build()) != null;
    }

    @Override
    public boolean deleteById(Long id) {
        List<LocationVo> children = this.selectListByParentId(id);
        if (!children.isEmpty()) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "有子级的位置数据无法删除，请先删除子级数据");
        }
        mapper.deleteByPrimaryKey(id);
        return true;
    }

    @Override
    public boolean updateName(LocationUpdateVo locationUpdateVo) {
        locationUpdateVo.setUpdateTime(DateTime.now());
        return mapper.updateName(locationUpdateVo);
    }

    @Override
    public List<Long> concatIdsByParentId(List<Long> ids, Long parentId) {
        List<LocationVo> locationVos = this.selectListByParentId(parentId);
        if (locationVos.isEmpty()) {
            return ids;
        }
        for (LocationVo locationVo : locationVos) {
            ids.add(locationVo.getId());
            ids = concatIdsByParentId(ids, locationVo.getId());
        }
        return ids;
    }

    @Override
    public List<Long> concatIdsByParentId(Long parentId) {
        List<Long> ids = new ArrayList<>();
        ids.add(parentId);
        return concatIdsByParentId(ids, parentId);
    }

    @Override
    public String selectNameByDeviceMsSn(String msSn) {
        return mapper.selectNameByDeviceMsSn(msSn);
    }

    @Override
    public Long selectLocationIdByDeviceMsSn(String msSn) {
        return mapper.selectLocationIdByDeviceMsSn(msSn);
    }

    @Override
    public StringBuilder concatNameByDeepId(Long id) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == id) {
            return stringBuilder;
        }
        PhLocation phLocation = this.selectById(id);
        if (null == phLocation) {
            return stringBuilder;
        }
        stringBuilder.append(phLocation.getName());
        return concatNameByDeepId(stringBuilder, phLocation.getParentId());
    }

    @Override
    public StringBuilder concatNameByDeepId(StringBuilder sourceName, Long parentId) {
        if (parentId == 0) {
            return sourceName;
        }
        PhLocation phLocation = this.selectById(parentId);
        sourceName.insert(0, phLocation.getName());
        return concatNameByDeepId(sourceName, phLocation.getParentId());
    }

    @Override
    public PhLocation selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public Long insert(PhLocation phLocation) {
        return mapper.insert(phLocation);
    }

    @Override
    public boolean update(PhLocation phLocation) {
        return mapper.update(phLocation);
    }

    @Override
    public List<LocationVo> selectListByCameraType(Byte cameraType) {
        List<LocationVo> locationVos = mapper.selectListByCameraType(cameraType);
        List<LocationVo> result = new LinkedList<>();
        if (!CollectionUtils.isEmpty(locationVos)) {
            //拼接一下全称
            locationVos.forEach(locationVo -> {
                StringBuilder stringBuilder = concatNameByDeepId(locationVo.getId());
                result.add(LocationVo.builder()
                        .name(stringBuilder.toString())
                        .id(locationVo.getId())
                        .parentId(locationVo.getParentId())
                        .build());
            });
        }
        return result;
    }

    /**
     * 生成树的方法
     */
    private List<LocationVo> createTree(List<LocationVo> list, Long pid, boolean isContainsCamera) {
        try {
            //根节点
            List<LocationVo> tempList = new ArrayList<>();
            for (LocationVo locationVo : list) {
                //父节点是0的，为根节点。
                if (Objects.equals(locationVo.getParentId(), pid)) {
                    tempList.add(locationVo);
                }
            }
            //为根id设置子childList是递归调用的
            for (LocationVo locationVo : tempList) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<LocationVo> childList = setChild(locationVo.getId(), list, isContainsCamera);
                //给根节点设置子节点
                locationVo.setChildren(childList);
            }
            // 输出构建好的菜单数据。
            return tempList;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    /**
     * 生成树的方法
     */
    private List<LocationVo> createTree(List<LocationVo> list, Long pid) {
        try {
            //根节点
            List<LocationVo> tempList = new ArrayList<>();
            for (LocationVo locationVo : list) {
                //父节点是0的，为根节点。
                if (Objects.equals(locationVo.getParentId(), pid)) {
                    tempList.add(locationVo);
                }
            }
            //为根id设置子childList是递归调用的
            for (LocationVo locationVo : tempList) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<LocationVo> childList = setChild(locationVo.getId(), list);
                //给根节点设置子节点
                locationVo.setChildren(childList);
            }
            // 输出构建好的菜单数据。
            return tempList;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    /**
     * 获取子菜单
     * 获取子节点
     *
     * @param id   父节点id
     * @param list 所有节点列表
     * @return 每个根节点下，所有子节点列表
     */
    private List<LocationVo> setChild(Long id, List<LocationVo> list) {
        //子节点
        List<LocationVo> childList = new ArrayList<>();
        for (LocationVo locationVo : list) {
            // 遍历所有节点，将所有子节点的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (locationVo.getParentId().equals(id)) {
                childList.add(locationVo);
            }
        }
        //递归
        for (LocationVo locationVo : childList) {
            locationVo.setChildren(setChild(locationVo.getId(), list));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.isEmpty()) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 获取子菜单
     * 获取子节点
     *
     * @param id               父节点id
     * @param list             所有节点列表
     * @param isContainsCamera 是否包含相机
     * @return 每个根节点下，所有子节点列表
     */
    private List<LocationVo> setChild(Long id, List<LocationVo> list, boolean isContainsCamera) {
        //子节点
        List<LocationVo> childList = new ArrayList<>();
//        for (LocationVo locationVo : list) {
//            // 遍历所有节点，将所有子节点的父id与传过来的根节点的id比较
//            //相等说明：为该根节点的子节点。
//            if (locationVo.getParentId().equals(id)) {
//                childList.add(locationVo);
//            }
//        }
//        //递归
//        for (LocationVo locationVo : childList) {
//            locationVo.setChildren(setChild(locationVo.getId(), list, isContainsCamera));
//        }
//        //如果节点下没有子节点，返回一个空List（递归退出）
//        if (childList.isEmpty()) {
//            if (isContainsCamera) {
//                return deviceService.selectCameraVoByLocationIdAndCameraType(id, Constants.CameraType.RECORDING);
//            } else {
//                return new ArrayList<>();
//            }
//        }
        return childList;
    }
}
